package com.yc.d0416;

import java.io.*;

public class MsgUtil {
    public static void sendText(String text , OutputStream out) throws IOException {
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(1);
        dos.writeUTF(text);
    }

    public static void sendFile(String filepath, OutputStream out) throws IOException {
        DataOutputStream dos = new DataOutputStream(out);
        dos.writeInt(2);
        //发送文件名
        File file = new File(filepath);
        dos.writeUTF(file.getName());
        byte[] bytes = new byte[1024];
        int count;
        try(FileInputStream fis = new FileInputStream(filepath)){
            while (((count = fis.read(bytes))) > -1 ){
                out.write(bytes, 0, count);
            }
        }
    }
    public static String recv(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(in);
        final  int i = dis.readInt();
        if(i == 1){
           return recvText(in);
        }else if(i == 2){
           return recvText(in);
        }
        return null;
    }

    private static String recvText(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(in);
        return dis.readUTF();
    }

    public static  String recvFile(InputStream in) throws IOException {
        DataInputStream dis = new DataInputStream(in);
        final String filename = dis.readUTF();
        byte[] bytes = new byte[1024];
        int count;
        String filepath = "d:/" + filename;
        try (FileOutputStream fos = new FileOutputStream(filepath)){
            while ((count = dis.read(bytes)) > -1 ){
                fos.write(bytes, 0, count);
            }
            return "接收到文件：" + filename;
        }
    }


}
